package com.web.server.common.filters;

import com.web.server.common.exception.CrmException;
import com.web.server.common.exception.StatusCode;
import com.web.server.common.response.Response;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by LILEI6 on 2016/8/1.
 */

@ControllerAdvice
public class ExceptionHandlers {
    private Logger log = Logger.getLogger(ExceptionHandlers.class);

    @ExceptionHandler
    @ResponseBody
    public Response handleException(BindException ex) {

        List<FieldError> fieldErrors = ex.getBindingResult().getFieldErrors();
        List<ObjectError> globalErrors = ex.getBindingResult().getGlobalErrors();
        List<String> errors = new ArrayList<>(fieldErrors.size() + globalErrors.size());
        String error;
        for (FieldError fieldError : fieldErrors) {

            error = (fieldError.getDefaultMessage().contains("NumberFormatException")?"请输入正确的数字！":fieldError.getDefaultMessage());
            errors.add(error);
        }
        for (ObjectError objectError : globalErrors) {
            error = objectError.getDefaultMessage();
            errors.add(error);
        }
        return new Response(StatusCode.STATUS_FAILURE, StringUtils.join(errors, "|"));
    }

    @ExceptionHandler
    @ResponseBody
    public Response handleException(MethodArgumentNotValidException ex) {
        return this.handleException(new BindException(ex.getBindingResult()));
    }


    @ExceptionHandler
    @ResponseBody
    public Response handleException(HttpMessageNotReadableException ex) {
        log.error(ex.getMessage(), ex);
        return new Response(StatusCode.STATUS_ARGUMENTS_INVALID, "参数不合法");
    }

    @ExceptionHandler
    @ResponseBody
    public Response handleException(CrmException ex) {
        log.error(ex.getMessage(), ex);
        return new Response(StatusCode.STATUS_FAILURE, ex.getMessage());
    }

    @ExceptionHandler
    @ResponseBody
    public Response handleException(Exception ex) {
        log.error(ex.getMessage(), ex);
        return new Response(StatusCode.STATUS_FAILURE, "请求错误！");
    }

}
